
import logging

from django.core.cache import cache
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from home.models import NavCategory, CourseCategory, Banner
from home.serializer import NavCategorySerializer, CourseCategorySerializer, BannerSerializer

logger = logging.getLogger('django')


# Create your views here.

# class HomeView(APIView):
#     def get(self, request):
#         logger.info('Hello World')
#         logger.error('Hello World')
#         logger.debug('Hello World')
#         return Response({'message': 'Hello World'})

class NavCateGoryAPIView(APIView):
    def get(self, request):
        """
        获取导航分类接口
        :param request:
        :return:
        """
        try:
            queryset = NavCategory.objects.filter(is_show=True, is_delete=False)
            ser = NavCategorySerializer(queryset, many=True)
            logger.info(f"成功获取导航分类列表,共{len(ser.data)}条记录")
            return Response({
                "code": 1,
                "message": "SUCCESS",
                "data": ser.data
            })

        except Exception as e:
            logger.error(f"获取导航分类列表失败,失败原因:{e}")
            return Response({
                "code": 0,
                "message": str(e),
                "data": []
            })
class CourseCateGoryAPIView(APIView):
    def get(self, request):
        """
        获取课程分类接口
        :param request:
        :return:
        """
        try:
            queryset = CourseCategory.objects.filter(is_show=True, is_delete=False, level=1).order_by('level')
            ser = CourseCategorySerializer(queryset, many=True)
            logger.info(f"成功获取课程分类列表,共{len(ser.data)}条记录")
            return Response({
                "code": 1,
                "message": "SUCCESS",
                "data": ser.data
                })
        except Exception as e:
            logger.error(f"获取课程分类列表失败,失败原因:{e}")
            return Response({
                "code": 0,
                "message": str(e),
                "data": []
                })
class BannerAPIView(APIView):
    def get(self, request):
        """
        获取轮播图接口
        :param request:
        :return:
        """
        try:
            #从Redis获取数据
            cache_key='shiyan0624:home:banner:list'
            banner_redis=cache.get(cache_key)
            if banner_redis:
                logger.info(f"成功从缓存中获取轮播图列表")
                return Response({
                    "code": 1,
                    "message": "SUCCESS FROM CACHE",
                    "data": banner_redis
                })
            #从MySQL获取数据
            queryset = Banner.objects.filter(is_show=True, is_delete=False)
            serializer=BannerSerializer(queryset,many=True)

            #把MySQL数据存入Redis
            cache.set(cache_key,serializer.data,timeout=60*60*24)
            logger.info(f"成功MySQL获取轮播图列表,更新到Redis，共{len(serializer.data)}条记录")
            return Response({
                "code": 1,
                "message": "SUCCESS from mysql",
                    "data": serializer.data
                })
        except Exception as e:
            logger.error(f"获取轮播图列表失败,失败原因:{e}")
            return Response({
                "code": 0,
                "message": str(e),
                "data": []
                })

